package com.iphone.extra;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.widget.TextView;

import com.iphone.extra.view.IWidgetFrameLayout;
import com.iphone.extra.view.ShortcutWidgetLayout;

public class WidgetMusicLayout extends IWidgetFrameLayout {

    private TextView mTitleView;

    public WidgetMusicLayout(Context context) {
        this(context, null, 0);
    }

    public WidgetMusicLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetMusicLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mTitleView = (TextView) findViewById(android.R.id.title);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.android.intent.action.MUSIC_PLAYER_INFO");
        getContext().registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onCellClicked(String describe) {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.android.music", "com.android.music.MusicBrowserActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            getContext().startActivity(intent);
            getContext().sendBroadcast(new Intent(ShortcutWidgetLayout.ACTION));
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public String getLabel(Resources res) {
        return res.getString(R.string.widget_label_music);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if ("com.android.intent.action.MUSIC_PLAYER_INFO".equals(action)) {
                boolean isPlaying = intent.getBooleanExtra("isPlaying", false);
                String artistName = intent.getStringExtra("music_artistName");
                String trackinfoName = intent.getStringExtra("music_trackinfoName");
                String albumName = intent.getStringExtra("music_albumName");
                if (trackinfoName != null) {
                    mTitleView.setText(trackinfoName);
                } else if (artistName != null) {
                    mTitleView.setText(artistName);
                }
            }
        }
    };
}
